/*
Kakine
ActionScript Framework
Copyright © 2011, PUNY, LLC.

This file is part of KAKINE.

KAKINE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

KAKINE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with KAKINE.  If not, see <http://www.gnu.org/licenses/>.
*/ 
package com.puny.utils
{
	public class Shuffler extends Object
	{
		private static var _map:Array;
		
		/**
		 * $Revision: 534 $<br/>
		 * Shuffle index numbers.
		 * Returns a random number but absolutely the number occurs once.
		 * @param length number of index
		 * @param times this class shuffles indexes <code>legnth x times</code> times 
		 */
		public function Shuffler(length:int,times:int=10) {
			if (_map == null || _map.length != length) {
				_map = new Array();
				for(var i:int = 0; i < length;i++) {
					_map.push(i);
				}
			}
			shuffle(times);
		}
		
		public function shuffle(times:int):void {
			var a:int;
			var b:int;
			var l:int = _map.length;
			for(var j:int = 0; j < l*times;j++) {
				a = Random.integer(l);
				b = Random.integer(l);
				swap(a,b);
			}
//			for each(var i:int in _map) {
//				trace(i);
//			}
		}

		private function swap(i:int,j:int):void {
			var tmp:int = _map[i];
			_map[i] = _map[j];
			_map[j] = tmp;
		}		
		
		/**
		 * Return shuffled index
		 * @return <code>i</code>th shuffled index number
		 */
		public function index(i:int):int {
			return _map[i];
		}
	}
}